﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using ProjectStudy.iTextSharpHeader;
using System.Text;
using iTextSharp.tool.xml;
using System.Net;

namespace ProjectStudy
{
    public partial class iTextPDF练习 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //指定字体库，并创建字体(宋体)
            BaseFont baseFont = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font font_zhCN = new iTextSharp.text.Font(baseFont, 9);

            Document doc = new Document();
            //Document doc1 = new Document(PageSize.A4);//设置A4大小
            //Document doc2 = new Document(PageSize.A4.Rotate());//设置A4横向
            //Document doc3 = new Document(PageSize.A5, 36, 72, 108, 180); //设置页面大小，同时设置上下左右页边距
            Rectangle pageSize = new Rectangle(644, 720);//设置页面宽高
            //pageSize.BackgroundColor = BaseColor.RED;//设置页面背景色
            //Document document = new Document(pageSize);
                        
            PdfWriter pw= PdfWriter.GetInstance(doc, new FileStream("C://PDF/Fly2.pdf", FileMode.Create));//生成PDF存放路径
            
            doc.SetPageSize(pageSize);
            string path = Server.MapPath("images/Image.jpg");
            iTextSharp.text.Image waterMark = iTextSharp.text.Image.GetInstance(path);
            waterMark.GrayFill = 20;//透明度，灰色填充
            //waterMark.Rotation//旋转
            //waterMark.RotationDegrees//旋转角度
            waterMark.SetAbsolutePosition(0,0);

            pw.Add(waterMark);
            
            //doc.Add(waterMark);

            //1.strength 是下面两个常量之一
            //PdfWriter.STRENGTH40BITS: 40 位  
            //PdfWriter.STRENGTH128BITS: 128位 (Acrobat Reader 5.0及以上版本支持)

            //2.UserPassword和ownerPassword 可以为空或零长度

            //3.Permissions 为下列常量之一：  
            //PdfWriter.AllowPrinting  
            //PdfWriter.AllowModifyContents  
            //PdfWriter.AllowCopy  
            //PdfWriter.AllowModifyAnnotations
            //PdfWriter.AllowFillIn  
            //PdfWriter.AllowScreenReaders
            //PdfWriter.AllowAssembly 
            //PdfWriter.AllowDegradedPrinting

            pw.SetEncryption(PdfWriter.STANDARD_ENCRYPTION_40, "123", "123456", PdfWriter.AllowPrinting);

            //页眉页脚
            Rectangle rect = new Rectangle(36, 54, 559, 788);
            rect.BorderColor = BaseColor.BLACK;
            pw.SetBoxSize("art", rect);
            //PdfReader pr = new PdfReader();
            
            //int pagecount= pr.NumberOfPages;
            HeaderFooter header = new HeaderFooter();
            pw.PageEvent = header;

            doc.Open();//打开文档
            
            //------------可选设置----------------------
            doc.AddTitle("This Title");//标题
            doc.AddSubject("This is Subject");//主题
            //doc.AddProducer();
            doc.AddLanguage("zh-CN");
            doc.AddKeywords("This is KeyWords");//关键字
            //doc.AddHeader("This is Name", "This is Content");//
            doc.AddCreator("This is Creator");//生成器
            doc.AddAuthor("This is Author");//作者
            //------------可选设置----------------------

            //Paragraph:段落，里面可以放Chunk、Phrase
            Paragraph p0 = new Paragraph("Hello World");
            doc.Add(p0);

            //使用FontFactory创建字体，字体风格不会被延续
            //使用Font创建字体，字体风格会被延续
            //Chunk:块，文本最小单位
            Chunk ck = new Chunk("Hello World",FontFactory.GetFont(FontFactory.COURIER,20,Font.ITALIC,new BaseColor(255,0,0)));
            Chunk chunk1 = new Chunk("This text is underlined",FontFactory.GetFont(FontFactory.HELVETICA, 12, Font.UNDERLINE)); 
            Chunk chunk2 = new Chunk("This font is of type ITALIC | STRIKETHRU", FontFactory.GetFont(FontFactory.HELVETICA, 12, Font.ITALIC | Font.NORMAL));

            //Phrase:语句
            Phrase pr2 = new Phrase("This is Phrase", FontFactory.GetFont(FontFactory.HELVETICA, 12, Font.ITALIC | Font.NORMAL));
            Paragraph p1 = new Paragraph(pr2);
            ck.SetBackground(new BaseColor(0xFF, 0xFF, 0x00));
            doc.Add(ck);
            doc.Add(chunk1);
            doc.Add(chunk2);
            doc.Add(p1);

            //外部链接
            Font link = FontFactory.GetFont("Arial", 12, Font.UNDERLINE,BaseColor.RED);
            Anchor ah = new Anchor("baidu",link);
            ah.Reference="https://www.baidu.com";
            
            //内部链接(锚点)
            Anchor anchor1 = new Anchor("This is an internal link"); anchor1.Name = "link1";
            Anchor anchor2 = new Anchor("Click here to jump to the internal link"); 
            anchor2.Reference = "#link1";

            Paragraph p2 = new Paragraph();
            Paragraph p3 = new Paragraph();
            Paragraph p4 = new Paragraph();
            p2.Add(ah);
            p3.Add(anchor1);
            p4.Add(anchor2);
            doc.Add(p2);
            doc.Add(p3);
            doc.Add(p4);

            //列表
            List list = new List(false, 10);//true：排序(会有1,2,3...)，false：不排序(会有-)，10为列表符号和内容间距

            //-------------不排序可以设置列表符号（三种方式）---------------
            //list.SetListSymbol("*");
            //list.ListSymbol = new Chunk("\u2022", FontFactory.GetFont(FontFactory.HELVETICA, 20));
            //list.ListSymbol = new Chunk(iTextSharp.text.Image.GetInstance("F://list.jpg"), 0, 0);
            //-------------不排序可以设置列表符号---------------

            //设置缩排                       
            list.Add(new iTextSharp.text.ListItem("First line"));
            list.Add(new iTextSharp.text.ListItem("The second line is longer to see what happens once the end of the line is reached. Will it start on a new line?")); 
            list.Add(new iTextSharp.text.ListItem("Third line"));            
            doc.Add(list);
            
            //注释  标题,内容
            Annotation a = new Annotation("authors","Maybe it's because I wanted to be an author myself that I wrote iText.");
            doc.Add(a);

            //表格
            Table aTable = new Table();
            PdfPTable tb1 = new PdfPTable(3);//设置表格为3列

            PdfPCell cell1 = new PdfPCell(new Phrase("姓名",font_zhCN));
            cell1.BackgroundColor = BaseColor.GRAY;//设置单元格背景色
            cell1.HorizontalAlignment = Element.ALIGN_CENTER;//设置单元格内容水平居中
            cell1.VerticalAlignment = Element.ALIGN_MIDDLE;//设置单元格内容垂直居中
            //cell1.BorderColor = BaseColor.RED;//设置单元格边框颜色
            //cell1.BorderWidth = 5;设置单元格边框宽度
            //cell1.Padding = 5;设置单元格内边距,上下左右均可设置            
            tb1.AddCell(cell1);

            cell1 = new PdfPCell(new Phrase("性别",font_zhCN));
            cell1.BackgroundColor = BaseColor.GRAY;//设置单元格背景色
            cell1.HorizontalAlignment = Element.ALIGN_CENTER;//设置单元格内容水平居中
            cell1.VerticalAlignment = Element.ALIGN_MIDDLE;//设置单元格内容垂直居中
            tb1.AddCell(cell1);
            cell1 = new PdfPCell(new Phrase("年龄",font_zhCN));
            cell1.BackgroundColor = BaseColor.GRAY;//设置单元格背景色
            cell1.HorizontalAlignment = Element.ALIGN_CENTER;//设置单元格内容水平居中
            cell1.VerticalAlignment = Element.ALIGN_MIDDLE;//设置单元格内容垂直居中
            tb1.AddCell(cell1);
            
            doc.Add(tb1);

            //图片
            string path2 = Server.MapPath("images/Image.jpg");
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(path2);
            img.Alignment = iTextSharp.text.Image.LEFT_ALIGN;//设置图片左对齐
            //img.SetAbsolutePosition(0, 0);//设置图片绝对位置
            img.ScaleAbsolute(100,100);//设置图片缩放
            //img.ScalePercent(50);//设置图片缩放
            //img.ScalePercent(50,60);//设置图片缩放
            //img.ScaleToFit(100,100);//设置图片缩放
            //img.Rotation = (float)Math.PI / 2;//图片旋转
            //img.RotationDegrees = 90f;//图片旋转
            img.GrayFill = 20;
            doc.Add(img);
            doc.NewPage();
            doc.Add(new Paragraph("123"));
            doc.Close();

            //PDFHelper.AddWatermarkWordHeaderPageNum("C://PDF/1.pdf",null, "C://PDF/2.pdf", "这是最新测试水印","这是页眉","这也是页眉",true);

            //PdfWriter.GetInstance(document, new FileStream("D://Fly2.pdf", FileMode.Create));
            //document.Open();
            //document.Add(new Paragraph("Hello World"));
            //document.Close();

            //XML文档转PDF
            WebClient wc = new WebClient();
            //从网址下载Html字串
            //string htmlText = Encoding.UTF8.GetString(wc.DownloadData(""));
            //byte[] pdfFile = this.ConvertHtmlTextToPDF(htmlText);
            //Response.Write(pdfFile);
            //return File(pdfFile, "application/pdf", "范例PDF档.pdf");

            //WaterMark.PDFWatermarkImg("D://Fly.pdf", "D://my.pdf", path2, 0, 0);
            //WaterMark.PDFWatermarkWord("D://my.pdf", "D://my2.pdf", "测试水印");
            //WaterMark.PDFWatermarkWordItalic("D://my.pdf", "D://my3.pdf", "斜体水印");
        }

        public byte[] ConvertHtmlTextToPDF(string htmlText)
        {
            if (string.IsNullOrEmpty(htmlText))
            {
                return null;
            }
            //避免当htmlText无任何html tag标签的纯文字时，转PDF时会挂掉，所以一律加上<p>标签
            htmlText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>  "+ htmlText;

            MemoryStream outputStream = new MemoryStream();//要把PDF写到哪个串流
            byte[] data = Encoding.UTF8.GetBytes(htmlText);//字串转成byte[]
            MemoryStream msInput = new MemoryStream(data);
            Document doc = new Document();//要写PDF的文件，建构子没填的话预设直式A4
            PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
            //指定文件预设开档时的缩放为100%
            PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
            //开启Document文件 
            doc.Open();
            //使用XMLWorkerHelper把Html parse到PDF档里

            //指定字体库，并创建字体(宋体)
            BaseFont baseFont = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font font_zhCN = new iTextSharp.text.Font(baseFont, 9);

            XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8);
            //将pdfDest设定的资料写到PDF档
            PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
            writer.SetOpenAction(action);
            doc.Close();
            msInput.Close();
            outputStream.Close();
            //回传PDF档案 
            return outputStream.ToArray();

        }

        
            
    }
}